package org.budo.warehouse.dao.impl;

import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.budo.mybatis.dao.MybatisDao;
import org.budo.support.dao.page.Page;
import org.budo.support.lang.util.MapUtil;
import org.budo.warehouse.dao.api.IMailBufferDao;
import org.budo.warehouse.service.entity.MailBuffer;
import org.springframework.stereotype.Repository;

/**
 * @author limingwei
 */
@Repository
public class MailBufferDaoImpl implements IMailBufferDao {
    @Resource
    private MybatisDao mybatisDao;

    @Override
    public Integer insert(MailBuffer mailBuffer) {
        return (Integer) mybatisDao.insert(MailBuffer.class, mailBuffer);
    }

    @Override
    public Integer countNotSentByPipelineId(Integer pipelineId) {
        String sql = " SELECT COUNT(1) FROM t_mail_buffer WHERE pipeline_id=#{pipelineId} AND ( sent_at IS NULL OR sent_at = '') ";
        Map<String, Object> parameter = MapUtil.stringObjectMap("pipelineId", pipelineId);
        return mybatisDao.findBySql(Integer.class, sql, parameter);
    }

    @Override
    public List<MailBuffer> listNotSentByPipelineId(Integer pipelineId, Page page) {
        String sql = " SELECT * FROM t_mail_buffer WHERE pipeline_id=#{pipelineId} AND ( sent_at IS NULL OR sent_at = '') ";
        Map<String, Object> parameter = MapUtil.stringObjectMap("pipelineId", pipelineId);
        return mybatisDao.listBySql(MailBuffer.class, sql, parameter, page);
    }

    @Override
    public Timestamp findNotSentMaxCreatedAtByPipelineId(Integer pipelineId) {
        String sql = " SELECT created_at FROM t_mail_buffer WHERE pipeline_id=#{pipelineId} ORDER BY created_at DESC LIMIT 1";
        Map<String, Object> parameter = MapUtil.stringObjectMap("pipelineId", pipelineId);
        return mybatisDao.findBySql(Timestamp.class, sql, parameter);
    }

    @Override
    public Integer updateSentAtByPipelineId(Timestamp sentAt, Integer pipelineId) {
        String sql = " UPDATE t_mail_buffer SET sent_at=#{sentAt} WHERE pipeline_id=#{pipelineId}";
        Map<String, Object> parameter = MapUtil.stringObjectMap("pipelineId", pipelineId, "sentAt", sentAt);
        return mybatisDao.updateBySql(sql, parameter);
    }
}